package webshowAjax;

import com.alibaba.fastjson.JSON;
import dao.Mescard;
import tools.InfoPack;
import utils.JDBCUtils;
import web.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MesgServlet extends BaseServlet {

    // 提供展示
    public void MesgShow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 修改编码格式
        req.setCharacterEncoding("UTF-8");		// 接受到的
        resp.setContentType("text/html; charset=UTF-8");		// 修改发送的



        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();
        // 创建sql语句

        // 根据发来的类型更改语句
        Mescard mescard = new Mescard();
        String ShowAction = req.getParameter("ShowAction");      // 隐藏input属性的标记
        String sql ="";
        if("Recer".equals(ShowAction)) {

            sql = "select b.mesgSender,a.userName as mesgSenderName,b.mesgMain " +
                    "from student a " + "join mescard b on a.userNum = b.mesgSender " +
                    "where b.mesgRecer = ? ;";


//             sql = "select * from mescard where mesgRecer = ?";
             mescard.setMesgRecer(req.getParameter("mesgRecer"));

        } else if ("Sender".equals(ShowAction)){
            sql = "select b.mesgRecer,a.userName as mesgRecerName,b.mesgMain " +
                    "from student a join mescard b on a.userNum = b.mesgRecer " +
                    "where b.mesgSender = ? ;";
//            sql = "select * from mescard where mesgSender = ?";

            mescard.setMesgSender(req.getParameter("mesgSender"));
        } else if ("RecerSender".equals(ShowAction)) {

            // 偷小懒，单对单的情况 即在 最近生日里面，此处可以知道双方的姓名，所以不做更新修改
            sql = "select * from mescard where mesgSender = ? and mesgRecer = ?";
            mescard.setMesgRecer(req.getParameter("mesgRecer"));
            mescard.setMesgSender(req.getParameter("mesgSender"));
        }

        // 与上sql问号一一对应


        try {
            pStatement = connection.prepareStatement(sql);

            if("Recer".equals(ShowAction)) {
                pStatement.setString(1, mescard.getMesgRecer());
            } else if ("Sender".equals(ShowAction)){
                pStatement.setString(1, mescard.getMesgSender());
            } else if ("RecerSender".equals(ShowAction)) {
                sql = "select * from mescard where mesgSender = ? and mesgRecer = ?";
                pStatement.setString(1, mescard.getMesgSender());
                pStatement.setString(2, mescard.getMesgRecer());

            }

            rsSet = pStatement.executeQuery();  // 获取结果
            resp.getWriter().append(InfoPack.RstoJson(rsSet)); // 发送(打包)
            // 然后将这个用户发给前端
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement,rsSet);	// 关闭连接
        }
    }







    // 呈交修改
    public void MesgUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Connection connection = null;
        PreparedStatement pStatement = null;

        String mesgSender = req.getParameter("mesgSender");
        String mesgRecer = req.getParameter("mesgRecer");
        String mesgMain = req.getParameter("mesgMain");
        try {
            String sql = "UPDATE mescard SET mesgMain = ? WHERE (mesgSender = ? and mesgRecer = ? and mesgNum>0)";
            connection = JDBCUtils.getConnection();
            pStatement = connection.prepareStatement(sql);

            pStatement.setString(1,mesgMain);
            pStatement.setString(2,mesgSender);
            pStatement.setString(3,mesgRecer);

            int count = pStatement.executeUpdate();
            if( count > 0) {
                System.out.println("修改成功");
                resp.getWriter().append("true");
//                resp.sendRedirect("/webdemo2/views/loginDemo.html");	// 改变地址栏 重定向
//				 req.getRequestDispatcher("/").forward(req, resp);		// 不会改变地址栏，传递请求
            }
            else {
                // 改为插入
                sql = "INSERT INTO mescard (mesgSender, mesgRecer, mesgMain) VALUES (?, ?, ?)";
                pStatement = connection.prepareStatement(sql);

                pStatement.setString(1,mesgSender);
                pStatement.setString(2,mesgRecer);
                pStatement.setString(3,mesgMain);

                count = pStatement.executeUpdate();
                if(count > 0) {
                    System.out.println("修改成功");
                    resp.getWriter().append("true");
                } else {
                    System.out.println("修改失败");
                    resp.getWriter().append("false");
                }

//                req.setAttribute("msg", "注册失败");
//                req.getRequestDispatcher("/Testfirst/views/fails.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("数据库插入失败");
            e.printStackTrace();
            req.setAttribute("msg", "注册失败");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
        } catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("信息不完整");
            req.setAttribute("msg", "注册失败,信息填写不完整");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
        } finally {
            JDBCUtils.close(connection, pStatement);
        }
    }

}
